#pragma once

#include <iostream>
#include <functional>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include <memory>

#include "Log.hpp"
#include "InetAddr.hpp"

namespace socket_ns
{
    using namespace log_ns;

    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;

    const static int gbacklog = 8;

    enum
    {
        SOCKET_ERROR = 1,
        BIND_ERROR,
        LISTEN_ERROR
    };

    // 模板方法模式
    class Socket
    {
    public:
        virtual void CreaterSocketOrDie() = 0;                                    // 创建套接字
        virtual void CreaterBindOrDie(uint16_t port) = 0;                         // 绑定套接字
        virtual void CreaterListenOrDie(int backlog = gbacklog) = 0;              // 监听套接字
        virtual int Accepter(InetAddr *cliaddr) = 0;                              // 获取连接
        virtual bool Connector(const std::string &peerip, uint16_t peerport) = 0; // 建立连接
        virtual int Sockfd() = 0;
        virtual void Close() = 0;

        virtual ssize_t Recv(std::string *out) = 0;      // 接收消息
        virtual ssize_t Send(const std::string &in) = 0; // 发送消息

        virtual void ReUserAddr() = 0; // 重用本地地址和端口
    public:
        // 创建监听套接字
        void BuildListenSocket(uint16_t port)
        {
            CreaterSocketOrDie(); // 创建
            ReUserAddr();
            CreaterBindOrDie(port); // 绑定
            CreaterListenOrDie();   // 监听
        }
        // 创建客户端套接字
        bool BuildClientSocket(const std::string &peerip, uint16_t peerport)
        {
            CreaterSocketOrDie(); // 创建
            return Connector(peerip, peerport);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {
        }
        TcpSocket(int sockfd) : _sockfd(sockfd)
        {
        }
        ~TcpSocket()
        {
        }
        // 创建套接字
        void CreaterSocketOrDie() override
        {
            // 创建socket
            _sockfd = ::socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create eror\n");
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "socket create success,sockfd: %d\n", _sockfd); // 3
        }
        // 绑定套接字
        void CreaterBindOrDie(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;

            // bind sockfd 和 socket addr
            if (::bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
            {
                LOG(FATAL, "bind eror\n");
                exit(BIND_ERROR);
            }
            // LOG(INFO, "bind success,sockfd: %d\n", _sockfd);
        }
        // 监听套接字
        void CreaterListenOrDie(int backlog) override
        {
            // 因为tcp是面向连接的，tcp需要未来不短地获取连接
            // 老板模式，随时等待被连接
            if (::listen(_sockfd, backlog) < 0)
            {
                LOG(FATAL, "listen eror\n");
                exit(LISTEN_ERROR);
            }
            // LOG(INFO, "listen success\n");
        }
        // 获取连接
        int Accepter(InetAddr *cliaddr) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            // 获取新连接
            int sockfd = ::accept(_sockfd, (struct sockaddr *)&client, &len);
            // 获取失败继续获取
            if (sockfd < 0)
            {
                LOG(WARNING, "sccept reeor\n");
                // return nullptr;
                return -1;
            }
            *cliaddr = InetAddr(client);
            LOG(INFO, "get a new link,client info: %s,sockfd:%d\n", cliaddr->AddrStr().c_str(), _sockfd);

            // return std::make_shared<TcpSocket>(sockfd); // C++14
            return sockfd;
        }
        // 建立连接
        bool Connector(const std::string &peerip, uint16_t peerport) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(peerport);
            // server.sin_addr.s_addr =
            ::inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

            // 与服务端建立连接
            int n = ::connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            // 也可以重连
            if (n < 0)
            {
                std::cerr << "connect socket error" << std::endl;
                return false;
            }
            return true;
        }
        // 获取_sockfd
        int Sockfd() override
        {
            return _sockfd;
        }
        // 关闭套接字
        void Close() override
        {
            if (_sockfd > 0)
            {
                ::close(_sockfd);
            }
        }

        // 接收消息
        ssize_t Recv(std::string *out) override
        {
            char inbuffer[4096];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                // *out = inbuffer;
                *out += inbuffer; // 调整(可能一次读取不成功 | 读取多次)
            }
            return n;
        }
        // 发送消息
        ssize_t Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }
        void ReUserAddr() override
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }

    private:
        int _sockfd; // 可以是listensock 也可以是普通sockfd
    };
}
